import treeUtils from "@/utils/treeUtils";
import {getByTableId} from "@/api/start/formEngine/formApi"
import {add, deleteById, page, updateById} from "@/api/start/formEngine/formDataApi"
import avueDataAdapter from "@/utils/avueDataAdapter";
import activitiFormUtils from "@/option/activitiFormUtils";
import startSearchModel from "../config/startSearchModel";
import startCrudTools from "./startCrudTools";

export default (app, option = {autoLoad: true}) => {

    if (option.autoLoad === null || option.autoLoad === undefined) {
        option.autoLoad = true;
    }
    let mixins = {
        computed: {
            bindVal() {
                return {
                    ref: 'crud',
                    option: this.tableOption,
                    data: this.dataSource,
                    tableLoading: this.loading
                }
            },
            onEvent() {
                return {
                    'on-load': this.loadRemoteDataSources,
                    'row-save': this.rowSave,
                    'row-update': this.rowUpdate,
                    'row-del': this.rowDel,
                    'refresh-change': this.refreshChange,
                    'search-reset': this.searchChange,
                    'search-change': this.searchChange
                }
            },
            option() {
                let temp = this.tableOption;
                let columns = temp.column;
                for (let i = 0; i < columns.length; i++) {
                    let column = columns[i];
                    let mapperName = column.component
                    if (!mapperName) {
                        if (!column.type) column.type = 'input';
                        mapperName = 'avue-' + column.type
                    }

                    if (column.slot) continue;
                    column.slot = true

                }
                return temp;
            },
            columns() {
                let temp = [];
                for (let i = 0; i < this.option.column.length; i++) {
                    let column = this.option.column[i];
                    temp.push(column);
                }
                return temp;
            },

        },
        data() {
            return {
                tableOption: null,
                dataSource: [],
                page: {
                    currentPage: 1,
                    pageSize: 10
                },
                tableId: null,
                loading: false,
                form: {},
                searchParams: {},
                columnsMap: {},
            }
        },

        created() {
            if (!option.autoLoad) {
                return
            }
            this.loadTableId();
            this.loadTableConfig();
        },
        methods: {
            loadTableId() {
                let route = this.$router.currentRoute;
                let path = route.path;
                let split = path.split("?")
                let indexOf = split[0].lastIndexOf("/")
                this.tableId = split[0].substr(indexOf + 1);
            },
            /**
             * 加载表单配置信息
             */
            loadTableConfig() {
                if (!this.tableId) return;
                getByTableId(this.tableId).then(result => {
                    let data = result.data.data;
                    try {
                        let option = data.formOption;
                        option = activitiFormUtils.handlerFormConfigVariable(option)
                        if (this.loadCrudOptionBefore) {
                            this.loadCrudOptionBefore(option)
                        }
                        let columns = option.column;
                        let map = {};
                        for (let i = 0; i < columns.length; i++) {
                            let column = columns[i];
                            if (this.loadCrudColumnBefore) {
                                this.loadCrudColumnBefore(column)
                            }
                            if (!column.search) continue;
                            map[column.prop] = column.searchModel ? column.searchModel : startSearchModel.EQ;
                        }
                        this.columnsMap = map;
                        this.tableOption = option
                        if (this.loadCrudOptionAfter) {
                            this.loadCrudOptionAfter(option)
                        }
                    } catch (e) {
                        console.error(e);
                    }
                });

            },
            /**
             * 加载列表配置
             */
            loadRemoteDataSources() {
                this.loading = true;
                if (this.beforeLoadDataSource) this.beforeLoadDataSource();
                this.dataSource = [];
                let pageParams = {}
                pageParams.current = this.page.currentPage
                pageParams.size = this.page.pageSize
                let searchParams = startCrudTools.getSearchParams(this.searchParams, this.columnsMap);
                if (this.beforeLoadDataSource) {
                    let tempSearchParams = this.beforeLoadDataSource(searchParams)
                    searchParams = tempSearchParams ? tempSearchParams : searchParams;
                }
                const requestData = Object.assign(pageParams, this.searchParams, searchParams)
                page(this.tableId, requestData).then(res => {
                    let data = res.data.data;
                    let tempListData;
                    if (data instanceof Array) tempListData = data;
                    if (!tempListData) {
                        tempListData = data[option.data || 'records'];
                        this.page.total = data[option.total || 'total'];
                    }
                    avueDataAdapter.transformDataList(this.tableOption.column, tempListData)
                    if (this.getListAfter) this.getListAfter(tempListData);
                    if (option.isTreeData) tempListData = treeUtils.listToTree(tempListData)
                    console.log("dataSource", tempListData)
                    this.dataSource = tempListData;

                }).finally(() => this.loading = false)

            },
            /**
             * 新增数据
             * @param row
             * @param done
             * @param loading
             */
            rowSave(row, done, loading) {
                avueDataAdapter.transformDataSave(this.tableOption.column, row)
                add(this.tableId, row).then((data) => {
                    this.loadRemoteDataSources()
                    this.$message.success('新增成功')
                }).finally(() => done())

            },
            /**
             * 修改数据
             * @param row
             * @param index
             * @param done
             * @param loading
             */
            rowUpdate(row, index, done, loading) {
                avueDataAdapter.transformDataSave(this.tableOption.column, row)
                updateById(this.tableId, row.id, row).then((data) => {
                    this.loadRemoteDataSources()
                    this.$message.success('更新成功')
                }).finally(() => done())
            },
            /**
             * 删除数据
             * @param row
             * @param index
             */
            rowDel(row, index) {
                this.$confirm(`此操作将永久删除序号为【${index + 1}】的数据！ 是否继续?`, '系统提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                }).then(() => deleteById(this.tableId, row.id)).then(res => {
                    this.loadRemoteDataSources()
                    this.$message.success('删除成功')
                })

            },
            /**
             * 搜索框参数变化
             * @param params
             * @param done
             */
            searchChange(params, done) {
                if (done) done();
                this.searchParams = params;
                this.page.currentPage = 1;
                this.loadRemoteDataSources()
            },
            /**
             * 刷新数据
             */
            refreshChange() {
                this.loadRemoteDataSources()
            }
        },

    }

    if (app.mixins === null || app.mixins === undefined) {
        app.mixins = []
    }
    app.mixins.push(mixins)
    return app;
}
